// Copyright 2010 Google Inc. All Rights Reserved.

/**
 * @fileoverview Discovery support.
 *
 * @author monsur@google.com (Monsur Hossain)
 */


/**
 * Loads the Discovery details for a particular version of an api and adds the
 * methods for that api into the global namespace.
 * @param {string} name The name of the api to load.
 * @param {string} version The version of the api to load.
 * @param {Function.<Object>} opt_callback An optional callback method to call
 *     once the new methods are created.  The parameter to this callback will be
 *     the new namespace (or an error object, if there was an error).
 */
googleapis.load = function(name, version, opt_callback) {
  var serviceName;
  var callback = opt_callback || function() {};

  // Loop through the Discover object and grab all the methods.
  var discoveryCallback = function(resp) {
    if (resp['error']) {
      callback(resp);
      return;
    }

    var processMethods = function(resp) {
      for (var name in resp) {
        if (!resp.hasOwnProperty(name)) {
          continue;
        }
        var methodName = resp[name]['rpcMethod'];
        // TODO(monsur): FYI, this puts the methods in the global namespace and
        // other locations.  See comments on googleapis.register() for more
        // details.
        googleapis.register(methodName);
        if (!serviceName) {
          // Pull the service name from the method, since they may not match
          // (as in the case of "buzz" vs. "chili").
          serviceName = googleapis.getServiceNameFromMethod(methodName);
        }
      }
    };

    var processResources = function(resp) {
      for (var name in resp) {
        if (!resp.hasOwnProperty(name)) {
          continue;
        }
        if (name === 'methods') {
          processMethods(resp[name]);
        } else if (name === 'resources') {
          for (var resource in resp[name]) {
            processResources(resp[name][resource]);
          }
        }
      }
    };

    processResources(resp);

    if (callback) {
      // Parameter to the callback is the newly created object.
      // Note that we currently create a new object on the global namespace
      // AND return the object here.  It'd be nice to consolidate on a single
      // mechanism, see comments on googleapis.register() for more details.
      callback.call(null, goog.getObjectByName(serviceName, osapi));
    }
  };

  // TODO(monsur): Investigate setting the version as a parameter
  // to newRequest()
  var versions = {'discovery': 'v0.2beta1'};
  versions[name] = version;
  googleapis.setVersions(versions);
  googleapis.newRequest('discovery.apis.get',
      {'api': name, 'version': version})
      .execute(discoveryCallback);
};
